package com.shop.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.common.core.domain.Result;
import com.shop.common.security.utils.SecurityUtils;
import com.shop.coupon.domain.Coupon;
import com.shop.coupon.domain.CouponHistory;
import com.shop.coupon.domain.vo.CouponHistoryVo;
import com.shop.coupon.mapper.CouponHistoryMapper;
import com.shop.coupon.mapper.CouponMapper;
import com.shop.coupon.service.CouponHistoryService;
import com.shop.coupon.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class CouponHistoryServiceImpl extends ServiceImpl<CouponHistoryMapper, CouponHistory> implements CouponHistoryService {

    private final CouponHistoryMapper couponHistoryMapper;

    public CouponHistoryServiceImpl(CouponHistoryMapper couponHistoryMapper) {
        this.couponHistoryMapper = couponHistoryMapper;
    }

    @Autowired
    private CouponService couponService;

    /**
     * 新用户注册赠券
     * @param couponHistory
     * @return
     */
    @Override
    public Result couponHistoryGift(CouponHistory couponHistory) {
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();

        // 使用数据库乐观锁，确保并发安全性
        CouponHistory existingHistory = couponHistoryMapper.selectById(userId);
        if (existingHistory != null) {
            return Result.error("此用户已经赠送过");
        }

        couponHistory.setCouponId(4L);
        couponHistory.setMemberId(userId);
        couponHistory.setMemberNickName(username);

        Integer historyGift = couponHistoryMapper.couponHistoryGift(couponHistory);
        return Result.success("新用户优惠券赠送成功" + historyGift);
    }


    /**
     * 手动领取优惠券
     * @param couponHistory
     * @return
     */
    @Override
    public Result couponDrawDown(CouponHistory couponHistory) {
        boolean alreadyExists = false;
        CouponHistory existingHistory = null;

        // 获取用户选择的优惠券
        Result<Coupon> result = couponService.getSelectCoupon();
        // 查询该优惠券的详细信息
        Result<Coupon> selectCoupon = couponService.getCoupon(couponHistory.getId());
        Coupon coupon = selectCoupon.getData();

        // 获取当前登录用户的用户名和ID
        String username = SecurityUtils.getUsername();
        Long userId = SecurityUtils.getUserId();

        // 设置优惠券领取历史记录的用户ID
        couponHistory.setMemberId(userId);

        // 查询当前用户的优惠券领取历史
        List<CouponHistory> couponHistories = baseMapper.selectList(couponHistory.getMemberId());
        // 判断是否已经领取过相同的优惠券
        for (CouponHistory history : couponHistories) {
            if (history.getCouponId().equals(coupon.getId())) {
                alreadyExists = true;
                existingHistory = history;
                break;
            }
        }
        // 判断当前卡包里的优惠券ID与要领取的优惠券ID是否相同\\\\\\\\\\
        if (!alreadyExists) {
            // 设置领取优惠券的详细信息
            couponHistory.setCouponId(coupon.getId());
            couponHistory.setMemberNickName(username);
            // 执行领取优惠券操作
            Integer drawDown = couponHistoryMapper.couponDrawDown(couponHistory);
            return Result.success(drawDown);
        }
        // 如果已经领取过相同的优惠券，检查是否需要更新领取数量
        if (coupon.getPerLimit() > existingHistory.getNumber()) {
            Integer couponNumUpd = couponHistoryMapper.couponNumUpd(existingHistory.getId());
            return Result.success(couponNumUpd);
        }
        // 若不满足以上条件，则返回优惠券已领取的错误信息
        return Result.error("该优惠券已经领取");
    }
}
